// pages/share_certification/share_certification.js
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    personal_list: [],
    identify_status: false,
    canvas_name: ''
  },
  onchangeStatus: function () {
    let that = this
    wx.request({
      url: 'https://gongzheng.ma.cn/Lapp/V1/init', //url
      method: 'POST', //请求方式
      header: {
        'Content-Type': 'application/json',
      },
      data: {

      },
      success: function (res) {
        console.log(res)
        let rtn = res.data
        if (rtn.code == 200) {
          that.setData({
            identify_status: rtn.data.face_veri
          })
        }
      },
      fail: function () {
        app.consoleLog("请求数据失败");
      },
      complete: function () {
        // complete 
      }
    })

  },
  choose_signature_files(e) {
    console.log(e)
    let that = this
    let index = e.currentTarget.dataset.index
    let order_id = e.currentTarget.dataset.order_id
    let type = e.currentTarget.dataset.type
    if (that.data.order_info.transfer_list[index].signature_path) return;
    wx.navigateTo({
      url: '../help_signature/help_signature?page=share_certification&type=' + type +'&index=' + index +'&order_id=' + order_id
    })
    
    // var that = this1
    // var index = e.currentTarget.dataset.index
    // if (this.data.personal_list[index].signature_path) return;
    // wx.navigateTo({
    //   url: '../help_signature/help_signature?page=help_transfer_info_personal&type=1&index=' + index
    // })


    // var index = e.currentTarget.dataset.index;
    // let that = this
    // if (that.data.order_info.transfer_list[index].signature_path) {
    //   wx.previewImage({
    //     urls: [that.data.order_info.transfer_list[index].signature_path]
    //   })
    // }
  },
  touchStart: function (e) {
    this.touchTimeStamp = e.timeStamp
  },
  
  touchEnd: function (e) {
    var diff = e.timeStamp - this.touchTimeStamp
    var tag = e.currentTarget.dataset.tag
    if (tag == 'signature_block') {
      diff >= 500 ? this.delete_signature_files(e) : this.preview_signature_files(e)
    }
  },
  delete_signature_files: function (e) {
    var index = e.currentTarget.dataset.index
    var that = this
    // if (that.data.order_info.transfer_list[index].signature_path) return;
    if (that.data.order_info.transfer_list[index].signature_path) {
      wx.showModal({
        title: '删除图片',
        content: '是否确认要删除该图片?',
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            
            let transferSign = that.data.order_info
            
            transferSign.transfer_list[index].signature_path = '';
            transferSign.transfer_list[index].signature_vc = '';
            
            that.setData({
              order_info: transferSign
            })
          }
        }
      })
    }
  },
  preview_signature_files: function (e) {
    var index = e.currentTarget.dataset.index;
    let that = this
    console.log(that.data.order_info.transfer_list[index].signature_path)
    if (that.data.order_info.transfer_list[index].signature_path) {
      wx.previewImage({
        urls: [that.data.order_info.transfer_list[index].signature_path]
      })
    }
  },
  upAndShowImg(tmpPath, index, type) {
    var that = this
    wx.uploadFile({
      url: util.reqUrl('V2/uploadSignature'),
      header: util.headers(),
      formData: { 'identity_token': util.getUserdata('identity_token'), 'rotate_angle': '0' },
      filePath: tmpPath,
      name: 'signature_' + index,
      success(res) {
        var rtn = JSON.parse(res.data)
        console.log('图片保存回来', rtn)

        let order_info = util.getUserdata('order_info')
        for (let i = 0; i < order_info.transfer_list.length; i++) {
          order_info.transfer_list[index].signature_vc = rtn.verify_code
          order_info.transfer_list[index].signature_path = 'https://gongzheng.ma.cn/MYPublic/' + rtn.image_path
        }

        let transferSign = util.getUserdata('transferSign')
        for (let i = 0; i < transferSign.length; i++) {
          transferSign[index].signature_vc = rtn.verify_code
          transferSign[index].signature_path = 'https://gongzheng.ma.cn/MYPublic/' + rtn.image_path
        }

        console.log('order_info', order_info)
        util.setUserdata('order_info', order_info)
        util.setUserdata('transferSign', transferSign)
        that.setData({
          order_info: order_info
        })

        // let transferSign = util.getUserdata('transferSign')
        // for (let i = 0; i < transferSign.length; i++) {
        //   transferSign[index].signature_vc = rtn.verify_code
        //   transferSign[index].signature_path = 'https://gongzheng.ma.cn/MYPublic/' + rtn.image_path
        // }
        // console.log(transferSign)
        // https://gongzheng.ma.cn/MYPublic/temps/20200814/5f3659794dd7d.png
        // util.setUserdata('transferSign', transferSign)
        // that.go_back()
      }
    })
  },
  saveImage() {
    var that = this
    wx.canvasToTempFilePath({
      canvasId: 'canvas-name',
      success(res) {
        console.log(res)
        that.upAndShowImg(res.tempFilePath, 1, 1)
        // wx.saveImageToPhotosAlbum({
        //   filePath: res.tempFilePath,
        //   success(res) {
        //     wx.showToast({
        //       title: '保存成功',
        //       icon: 'success'
        //     })
        //   }
        // })
      }
    })
  },
  
  getCanvasName: function() {
    // let temp_tempFilePath = ''
    setTimeout(() => {
      wx.canvasToTempFilePath({
        canvasId: 'canvas-name',
        success(res) {
          console.log('canvasName', res.tempFilePath)
          // temp_tempFilePath = res.tempFilePath
          return res.tempFilePath
        }
      })
    },500)
    
    // return temp_tempFilePath
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // wx.clearStorage()
    let that = this
    
    console.log(options)
    //{id:1216}
    this.setData({
      order_id: options.id
      // update: options.update
    })
    // util.setUserdata('help_order_update', options.update)
    // console.log(util.getUserdata('help_order_update'))
    console.log(this.data.order_id)
    util.request('V2/orderInfo',
      {
        'order_id': this.data.order_id
      },
      function (res) {
        if (res.data.code == 0) {
          console.log('识别完再进入')
          console.log(res.data.order_info);
          let transferSign = util.getUserdata('transferSign')
          console.log(transferSign)

          let share_receive_list = res.data.order_info.receive_list
          let share_transfer_list = res.data.order_info.transfer_list
          
          if (transferSign.length > 0 && that.data.order_id == res.data.order_info.order_id) {
            for (let m = 0; m < share_transfer_list.length; m++) {
              share_transfer_list[m].apply_no = transferSign[m].apply_no || '0'
              share_transfer_list[m].verifycode = transferSign[m].verifycode || '0'
              share_transfer_list[m].signature_path = transferSign[m].signature_path
              share_transfer_list[m].signature_vc = transferSign[m].signature_vc
            }
            console.log(transferSign)
            console.log(share_transfer_list)
          }
          
          // res.data.order_info.transfer_list = share_transfer_list


          let share_brand_info = {}
          share_brand_info.address = res.data.order_info.address
          let brand_files = []
          let brand_vc = []
          for (var i = 0; i < res.data.order_info.brand_image_list.length; i++) {
            brand_files.push('https://gongzheng.ma.cn/MYPublic/' + res.data.order_info.brand_image_list[i].image_path)
            brand_vc.push(res.data.order_info.brand_image_list[i].brand_vc)
          }
          console.log(brand_files)
          share_brand_info.brand_files = brand_files
          share_brand_info.brand_vc = brand_vc

          let brand_other_files = []
          let brand_other_vc = []
          for (var k = 0; k < res.data.order_info.brand_other_image_list.length; k++) {
            brand_other_files.push('https://gongzheng.ma.cn/MYPublic/' + res.data.order_info.brand_other_image_list[k].image_path)
            brand_other_vc.push(res.data.order_info.brand_other_image_list[k].brand_other_vc)
          }
          share_brand_info.brand_other_files = brand_other_files
          share_brand_info.brand_other_vc = brand_other_vc

          share_brand_info.brand_register_code = res.data.order_info.brand_register_code
          share_brand_info.brand_name = res.data.order_info.brand_name
          share_brand_info.other_possessor = res.data.order_info.other_possessor
          share_brand_info.possessor_name = res.data.order_info.possessor_name
          share_brand_info.type_num = res.data.order_info.type_num
          share_brand_info.validity = res.data.order_info.validity

          let share_other = {}
          share_other.care_type = res.data.order_info.care_type == 0 ? false : true
          share_other.comm_type = res.data.order_info.comm_type == 0 ? false : true
          share_other.mail_type = res.data.order_info.mail_type == 0 ? false : true
          share_other.page_count = res.data.order_info.page_count
          share_other.remark = res.data.order_info.remark


          util.setUserdata('order_info', res.data.order_info)
          console.log('重新进来')
          util.setUserdata('share_transfer_list', res.data.order_info.transfer_list)
          util.setUserdata('transferSign', share_transfer_list)//签名 和识别
          util.setUserdata('share_receive_list', res.data.order_info.receive_list)
          util.setUserdata('share_brand_info', share_brand_info)
          util.setUserdata('share_other', res.data.order_info.share_other)
          util.setUserdata('order_id', res.data.order_info.order_id)
          util.setUserdata('member_id', res.data.order_info.member_id)
          util.setUserdata('share_order_close', res.data.order_info.close_status)

          let update_status = ''
          if (res.data.order_info.order_status == 6) {
            update_status = 'true'
          } else {
            update_status = 'false'
          }
          util.setUserdata('help_order_update', update_status)
          console.log(res.data.order_info);
          that.setData({
            // transfer_ohter: transfer_ohter,
            // receive_ohter: receive_ohter,
            // share_transfer_info: share_transfer_info,
            // share_transfer_list: share_transfer_list,
            // share_brand_info: share_brand_info,
            // share_receive_list: share_receive_list,
            // share_other: share_other,
            order_info: res.data.order_info,
            // member_id: res.data.order_info.member_id,
            // order_id: res.data.order_info.order_id,
            // order_status: res.data.order_info.close_status
            // page_money: page_money,
            // other_money: other_money,
            // all_money: all_money,
            // vip_money: vip_money,
            // vip_status: app.globalData.member.is_vip
          })
        } else {
          console.log(res.data.code)
          let dataCode = res.data.code < 0 ? 1 : 2
          that.setData({
            order_status: dataCode
          })
        }
      },
      function (res) {
        //尝试重启
        wx.reLaunch({
          url: 'pages/index/index'
        })
      },
      function (res) {
        // wx.hideToast();
      })


    //改变状态
    this.onchangeStatus()
  },


  bindCommitCertification: function (e) {
    let that = this
    let tempStatus = that.data.identify_status
    // let formId = e.detail.formId;
    let formId = that.data.order_info.wx_tmpl_formid;
    let openId = that.data.order_info.wx_openid

    let share_transfer_list = that.data.share_transfer_list
    let share_receive_list = that.data.share_receive_list
    let share_brand_info = that.data.share_brand_info
    // let share_other = that.data.share_other
    let order_id = that.data.order_id
    let member_id = that.data.member_id
    let order_info = that.data.order_info

    let share_other = {}
    share_other.care_type = order_info.care_type == 0 ? false : true
    share_other.comm_type = order_info.comm_type == 0 ? false : true
    share_other.mail_type = order_info.mail_type == 0 ? false : true
    share_other.page_count = order_info.page_count
    share_other.remark = order_info.remark

    for (let i = 0; i < share_transfer_list.length; i++) {
      share_transfer_list[i].verifycode = share_transfer_list[share_transfer_list.length-1].verifycode
    }

    console.log(order_info)
    // console.log(share_transfer_info)
    console.log(share_transfer_list)
    console.log(share_receive_list)
    console.log(share_brand_info)
    console.log('share_other', share_other)
    console.log(order_id)
    console.log(member_id)

    if (tempStatus == true) {
      let msg = that.face_checked(order_info.transfer_list)
      if (msg != '') {
        wx.showModal({
          content: msg,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            }
          }
        })
        return
      }

      wx.showLoading({
        title: '订单认证中',
        icon: 'loading',
        duration: 10000,
        mask: true
      })

      let update_status = util.getUserdata('help_order_update')
      console.log(update_status)
      let stepUpdate = ''
      if (update_status == 'true') {
        stepUpdate = 'modify_commit'
      } else {
        stepUpdate = 'verify'
      }


      console.log(order_info.transfer_list)
      // return false
      util.request('V2/commitOrder2',
        {
          'other': JSON.stringify(share_other),
          'order_id': order_id,
          'brand_info': JSON.stringify(share_brand_info),
          // 'transfer_info': JSON.stringify(share_transfer_list),
          'transfer_info': JSON.stringify(order_info.transfer_list),
          'receive_info': JSON.stringify(share_receive_list),
          'wx_tmpl_formid': formId,
          'wx_openid': openId,
          'member_id': member_id,
          'delivery_name': that.data.order_info.delivery_name,
          'delivery_mobile': that.data.order_info.delivery_mobile,
          'delivery_addr': that.data.order_info.delivery_addr,
          'step': stepUpdate
          // 'wx_openid': openId,
        },
        function (res) {
          var rtn = res
          console.log(res.data)
          that.setData({
            resMsg: JSON.stringify(res.data)
          })
          wx.hideLoading()
          if (rtn.data.code == 1 || rtn.data.code == 0) {
            wx.showToast({
              title: '认证成功,请完成付款',
              icon: 'none',
              duration: 2000
            })

            util.removeUserData('share_order_id')
            util.removeUserData('help_transfer_info_apply_nos')//清空本地applyno
            util.removeUserData('share_transfer_info')
            util.removeUserData('help_transfer_info')
            util.removeUserData('share_order_info')
            util.removeUserData('share_share_other')
            util.removeUserData('share_brand_info')
            util.removeUserData('share_receive_list')
            util.removeUserData('share_transfer_info')
            util.removeUserData('transferSign')
            util.removeUserData('delivery')
            

            that.setData({
              order_status: 1
            })
            if (rtn.data.order_id) {
              if (stepUpdate == 'verify') {
                wx.reLaunch({
                  url: '../my_order/my_order?status=1'
                })
              } else if (stepUpdate == 'modify_commit') {
                wx.reLaunch({
                  url: '../my_order/my_order?status=2,4,6'
                })
              }

            }

          }else{
            wx.showModal({
              content: res.data.msg,
              showCancel: false,
              success: function (result) {
                if (result.confirm) {
                }
              }
            })
            return
          }
        }
      )
    } else {
      util.request('V1/toVerify',{'type':1},
        function (res) {
          if (res.data.code == 200) {
            wx.showToast({
              title: '认证成功,请完成付款',
              icon: 'none',
              duration: 2000,
              success: function () {
                wx.reLaunch({
                  url: '../my_order/my_order?status=1'
                })
              }
            })
          }
        },
        function (res) {
          //尝试重启
          wx.reLaunch({
            url: 'pages/index/index'
          })
        },
        function (res) {
          // wx.hideToast();
        }
      )
      
    }

    
  },
  face_checked(obj) {
    let returnMsg = ''
    console.log(obj)
    for(let i = 0; i < obj.length; i++) {
      if (obj[i].transfer_type == 1) {
        if (obj[i].signature_path == '' && obj[i].signature_vc == '') {
          returnMsg += '请' + obj[i].personal_name + '用户进签名'
          return returnMsg
        }
        if (obj[i].verifycode == '' || obj[i].apply_no == '' || obj[i].verifycode == '0' || obj[i].apply_no == '0') {
          returnMsg += '请' + obj[i].personal_name + '用户进行身份认证'
          return returnMsg
        }
      } else if (obj[i].transfer_type == 2) {
        if (obj[i].signature_path == '' && obj[i].signature_vc == '') {
          returnMsg += '请' + obj[i].company_personal_name + '用户进签名'
          return returnMsg
        }
        if (obj[i].verifycode == '' || obj[i].apply_no == '' || obj[i].verifycode == '0' || obj[i].apply_no == '0') {
          returnMsg += '请' + obj[i].company_personal_name + '用户进行身份认证'
          return returnMsg
        }
      } else if (obj[i].transfer_type == 3) {
        if (obj[i].signature_path == '' && obj[i].signature_vc == '') {
          returnMsg += '请' + obj[i].company_personal_name + '用户进签名'
          return returnMsg
        }
        if (obj[i].verifycode == '' || obj[i].apply_no == '' || obj[i].verifycode == '0' || obj[i].apply_no == '0') {
          returnMsg += '请' + obj[i].company_personal_name + '用户进行身份认证'
          return returnMsg
        }
      }
      
    }
    return returnMsg
  },
  identify_check(e) {
    console.log(e.currentTarget.dataset)
    let that = this
    let index = e.currentTarget.dataset.index

    let share_transfer_list = that.data.order_info.transfer_list
    
    console.log(share_transfer_list)
    let name = ''
    let identity_code = ''
    if (share_transfer_list[index].transfer_type == 1) {
      name = share_transfer_list[index].personal_name
      identity_code = share_transfer_list[index].identity_code
    } else if (share_transfer_list[index].transfer_type == 2) {
      name = share_transfer_list[index].company_personal_name
      identity_code = share_transfer_list[index].company_identity_code
    } else if (share_transfer_list[index].transfer_type == 3) {
      name = share_transfer_list[index].company_personal_name
      identity_code = share_transfer_list[index].company_identity_code
    }

    console.log(name)
    console.log(identity_code)

    // let share_transfer_info = util.getUserdata('share_transfer_info')
    // if (share_transfer_info.length < 1){
    //   wx.showToast({
    //     title: '请先授权签名',
    //     icon: 'none',
    //     duration: 3000
    //   })
    //   return false
    // }

    console.log(that.data.order_info.transfer_list)
    util.setUserdata('help_transfer_info', that.data.order_info.transfer_list)
    console.log("第" + index + "个转让人");
    util.setUserdata('help_transfer_info_GetToken_index', index + 1);

    let apply_no = "";
    if (Object.keys(util.getUserArr('help_transfer_info_apply_nos')).length !== 0) {
      apply_no = util.getUserArr('help_transfer_info_apply_nos');
    }
    console.log('transfer_info_apply_nos==')
    console.log(util.getUserArr('help_transfer_info_apply_nos'))

    console.log('apply_no', apply_no)
    util.request('V3/GetToken',
      {
        'name': name,
        'identity_code': identity_code,
        'apply_no': apply_no
        // 'apply_no': ''
      },
      function (res) {
        console.log("第" + util.getUserArr('help_transfer_info_GetToken_index') + "个获取GetToken结果");
        console.log(res)
        if (res.data.code == 0) {
          console.log(res.data.access_token)
          console.log(res.data.apply_no)
          let transferSign = util.getUserArr('transferSign')


          console.log(66666)
          // console.log(transfer_info)
          console.log(transferSign)
          console.log(util.getUserArr('help_transfer_info_GetToken_index'))
          console.log(util.getUserArr('help_transfer_info_apply_nos'))
          console.log(Object.keys(util.getUserArr('help_transfer_info_apply_nos')).length)
          console.log(66666)

          if (Object.keys(util.getUserArr('help_transfer_info_apply_nos')).length !== 0) {
            console.log("help_transfer_info_apply_nos已存在值")
            console.log(util.getUserArr('help_transfer_info_apply_nos'))
            // transfer_info[util.getUserArr('transfer_info_GetToken_index') - 1].apply_no = util.getUserArr('transfer_info_apply_nos');//apply_no赋值
            
            // transfer_info[util.getUserArr('help_transfer_info_GetToken_index') - 1].apply_no = res.data.apply_no;
            transferSign[util.getUserArr('help_transfer_info_GetToken_index') - 1].apply_no = res.data.apply_no;
          } else {
            console.log("给help_transfer_info_apply_nos赋值")
            util.setUserdata('help_transfer_info_apply_nos', res.data.apply_no);
            // transfer_info[util.getUserArr('help_transfer_info_GetToken_index') - 1].apply_no = res.data.apply_no; //apply_no赋值
            transferSign[util.getUserArr('help_transfer_info_GetToken_index') - 1].apply_no = res.data.apply_no; //apply_no赋值
          }

          console.log('look', transferSign)
          // util.setUserdata('share_transfer_info', transfer_info)
          util.setUserdata('transferSign', transferSign)

          wx.navigateToMiniProgram({
            appId: 'wxe13612bab6414ea4',
            path: '/pages/idverification/idverification',
            envVersion: 'release',
            extraData: {
              'token': res.data.access_token, //身份凭证accessToken
              'applyNo': res.data.apply_no,//订单号applyNo
              'name': name, //当事人姓名
              'idno': identity_code //当事人身份证号码
            },
            success(res) {
              console.log("调用外部小程序回调数据");
              console.log(res);
            },
            fail(res) {
              // that.setData({
              //   isButtonClick: false
              // })
            },
            complete(res) {
              // that.setData({
              //   isButtonClick: false
              // })
            }
          });

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1000
          });
        }
      });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成
    
  },
  buildSign: function(e) {
    let that = this

    let index = e.currentTarget.dataset.index
    // let order_id = e.currentTarget.dataset.order_id
    let type = e.currentTarget.dataset.type

    let order_info = util.getUserdata('order_info')
    console.log("orderinfo", order_info)
    console.log("index", e.currentTarget.dataset.index)
    console.log("type", e.currentTarget.dataset.type)
    let name = ''

    order_info.transfer_list[index].personal_name

    if (type == 1) {
      name = order_info.transfer_list[index].personal_name
    } else if (type == 2) {
      name = order_info.transfer_list[index].company_personal_name
    } else if (type == 3) {
      name = order_info.transfer_list[index].company_personal_name
    }

    wx.downloadFile({
      url: 'https://gongzheng.ma.cn/Lapp/V2/create_sign/font/'+name,
      success: (res) => {
        console.log('loadimg', res)
        that.upAndShowImg(res.tempFilePath, index, type)
        // let image = res.tempFilePath;
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    console.log(options)
    let that = this

    let order_info = util.getUserdata('order_info')
    let share_transfer_info = util.getUserdata('share_transfer_info')//人脸返回
    var myindex = util.getUserArr('transferIndex'); 

    let transferSign = util.getUserArr('transferSign')

    let share_transfer_list = util.getUserdata('share_transfer_list')
    let share_receive_list = util.getUserdata('share_receive_list')
    let share_brand_info = util.getUserdata('share_brand_info')
    let share_other = util.getUserdata('share_other')
    let order_id = util.getUserdata('order_id')
    let member_id = util.getUserdata('member_id')


    // for (let i = 0; i < transferSign.length; i++) {
    //   if (transferSign[i].verifycode != 0) {
    //     transferSign[i].verifycode = transferSign[myindex-1].verifycode
    //   }

    // }


    if (share_transfer_info) {
      // order_info.transfer_list = share_transfer_info
      order_info.transfer_list = transferSign

      that.setData({
        share_transfer_list: share_transfer_info,
        share_receive_list: share_receive_list,
        share_brand_info: share_brand_info,
        share_other: share_other,
        order_id: order_id,
        member_id: member_id,
        order_info: order_info
      })
    }
    
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})